import React, { useState, useEffect, useContext, useCallback } from 'react'

import { 
  View, 
  Map,
  CoverImage,
  Navigator
} from '@tarojs/components'

import Taro, { useDidShow } from '@tarojs/taro'

import minipetContext from '../../context/minipet-db'

import { IndexWrap } from './styledIndex'

import center from '../../assets/images/center.png'

export default function Index() {
  let map = null
  
  let [longitude, setLongitude] = useState(0)
  let [latitude, setLatitude] = useState(0)
  let [markers, setMarkers] = useState([])

  useDidShow(() => {
    loadData()
  })

  let minipet = useContext(minipetContext)

  const loadData = useCallback(() => {
    minipet.get({
      success: (res) => {
        const markers = res.data.map(value => {
          let {
            _id,
            latitude,
            longitude,
            message,
            type
          } = value

          return {
            id: _id,
            latitude,
            longitude,
            title: message,
            iconPath: require(`../../assets/images/${type}.png`),
            width: 40,
            height: 40
          }
        })

        setMarkers(markers)
      }
    })
  }, [])

  const handleLocationTap = useCallback(() => {
    map.moveToLocation()
  }, [])

  const handlePublishTap = useCallback(() => {
    Taro.navigateTo({
      url: '/pages/publish/publish',
    })
  }, [])

  const handleMarkerTap = useCallback((e) => {
    Taro.navigateTo({
      url: '/pages/detail/detail?id=' + e.markerId,
    })
  }, [])

  useEffect(() => {
    Taro.getLocation({
      type: 'wgs84',
      success: (res) => {
        let {
          longitude,
          latitude
        } = res

        setLongitude(longitude)
        setLatitude(latitude)
      }
    })

    map = Taro.createMapContext('map')

    // loadData()
  }, [])

  return (
    <IndexWrap>
      <View class="map-wrap">
        <View class="map">
          <Map 
            id="map"
            longitude={longitude}
            latitude={latitude}
            markers={markers}
            scale="16"
            onMarkerTap={handleMarkerTap}
            show-location
          >
            <CoverImage
              src={center}
              class="cover-image"
              onClick={handleLocationTap}
            ></CoverImage>
          </Map>
        </View>
        <View class="nav">
          <View onClick={handlePublishTap}>
            发布
          </View>
            <View>
              <Navigator url="/pages/search/search" open-type="navigateTo">
                搜索
              </Navigator>
            </View>
        </View>
      </View>
    </IndexWrap>
  )
}
